package com.tinywind.boot.common.config;

import com.tinywind.boot.common.base.BaseResult;
import com.tinywind.boot.common.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author liuxingyu01
 * @date 2021-12-25-9:40
 * @description 全局异常处理
 **/
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 自定义异常
     */
    @ExceptionHandler(CustomException.class)
    public BaseResult customException(CustomException e) {
        return BaseResult.failure(e.getCode(), e.getMessage());
    }


    /**
     * 404异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public BaseResult handlerNoFoundException(Exception e) {
        return BaseResult.failure(404, "路径不存在，请检查路径是否正确!");
    }

    /**
     * 字段验证异常
     */
    @ExceptionHandler(BindException.class)
    public BaseResult bindException(BindException e) {
        return BaseResult.failure(e.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        return BaseResult.failure(e.getBindingResult().getFieldError().getDefaultMessage());
    }

}
